import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap, Router } from '@angular/router';

import { switchMap } from 'rxjs/operators';

import { UISelected } from '../core/types/ui-selected.type';
import { Hero } from './shared/hero.model';
import { HeroService } from './shared/hero.service';
import { Power } from './shared/power.model';

@Component({
    selector: 'my-heroes',
    templateUrl: './heroes.component.html',
    styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
    selectedHero: Hero;
    heroes: Hero[] = [];
    filteredHeroes = this.heroes;
    private selectedId: number;

    constructor(
        private router: Router,
        private route: ActivatedRoute,
        private heroService: HeroService
    ) { }

    ngOnInit(): void {
        // IMPORTANT!!!
        // The code inside the switchMap will not be triggered until the returned 
        // data is used, like being accessed on the page or subscribed.
        // The switchMap operator also cancels previous in-flight requests. If the user re-navigates to this 
        // route with a new id while the HeroService is still retrieving the old id, switchMap discards that old 
        // request and returns the hero for the new id.
        this.route.paramMap
            .pipe(switchMap((params: ParamMap) => {
                // (+) before `params.get()` turns the string into a number.
                this.selectedId = +params.get('id');

                // You can get the Object from the string.
                let hero = JSON.parse(params.get('hero'));

                return Promise.resolve();
            })).toPromise();

        // this.route.paramMap.subscribe((params: ParamMap) => { 
        //   this.selectedId = +params.get('id');
        // });

        this.getHeroes();

        // Extends a model when needed without update its properties.
        let newData: Power & UISelected = { id: 1, name: 'test', selected: true };
        this.testPower(newData);
    }

    testPower(p: Power): void {
        console.dir(p);
    }

    trackByHeroes = this.heroService.trackByHeroes;

    getHeroes(): void {
        // this.heroService.getHeroes().then(heroes => this.heroes = heroes);

        // this.heroService.getHeroesAsync().then(heroes => this.heroes = heroes);

        // this.heroService.getHeroes2((heroes: Hero[]) => {
        //   this.heroes = heroes;
        // });
    }

    onSelect(hero: Hero): void {
        this.selectedHero = hero;
    }

    // Selects the hero by id passed from detail page as optional parameter.
    isSelected(hero: Hero): boolean {
        return hero.id === this.selectedId;
    }

    gotoDetail(id: number): void {
        this.router.navigate(['/heroes/detail', id]);
    }

    add(name: string): void {
        name = name.trim();

        if (!name) {
            return;
        }

        // this.heroService.create(name)
        //   .then(hero => {
        //     this.heroes.push(hero);
        //     this.selectedHero = null;
        //   });
    }

    // heroName: string = 'Testing Hero';

    // addHero(): void {
    //   console.log(this.heroName);
    // }

    delete(hero: Hero): void {
        //   this.heroService
        //     .delete(hero.id)
        //     .then(() => {
        //       this.heroes = this.heroes.filter(h => h !== hero);

        //       if (this.selectedHero === hero) {
        //         this.selectedHero = null;
        //       }
        //     })
    }

    onDeleteRequest(hero: Hero): void {
        console.log(`Event captured from child component...${hero.name}`);
    }

    onFilterChanged(searchText: string): void {

    }
}